#include <stdlib.h>
#include <errno.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include "admin.h"
int sockfd,acceptfd;
int flag = 1;
int main(int argc,char *argv[])
{
	int rlen;
	char buf[128];
	
/*	printf("database open successfully\n");
	ret=sqlite3_exec(db,"create table employee\
	(name char,age char,tel char,addr char,\
	job char,date char,salary char,grade char);",NULL,NULL,&errmsg);
    if(ret!=0)
    {
        perror("table create err");
		printf("ret = %d\n",ret);
        return -1;
    }
	ret=sqlite3_exec(db,"create table account\
	(key char,account char,password char);",NULL,NULL,&errmsg);
    if(ret!=0)
    {
        perror("table create  account err");
		printf("ret = %d\n",ret);
        return -1;
    }
	printf("table account create successfully\n");
	ret=sqlite3_exec(db,"create table history\
	(key char,account char,date char);",NULL,NULL,&errmsg);
    if(ret!=0)
    {
        perror("table create err");
		printf("ret = %d\n",ret);
        return -1;
    }
	printf("table history create successfully\n");
	*/
	sockfd = socket(AF_INET,SOCK_STREAM,0);//
	if(sockfd < 0)
	{
		perror("sockfd create error");
		return -1;
	}
	printf("sockfd create\n");
	struct sockaddr_in serveraddr,clientaddr;
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(argv[2]));
	serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
	socklen_t addrlen = sizeof(serveraddr);
	//解决端口复用
	int optval = 1;
	socklen_t optval_len = sizeof(optval);
	setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&optval,optval_len);


	if(bind(sockfd,(struct sockaddr *)&serveraddr,addrlen) < 0)
	{
		perror("bind error");
		return -1;
	}
	printf("bind successful\n");
	if(listen(sockfd,10) < 0)
	{
		perror("bind error");
		return -1;
	}
	int epfd,eptc,i;
	struct epoll_event event;//定义epoll事件
	struct epoll_event events[20];//定义epoll事件集合
	epfd = epoll_create(1);//定义epoll的fd

	event.data.fd = sockfd;//填充事件的fd
	event.events = EPOLLIN | EPOLLET;//填充时间类型
	epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event);//把sockfd注册到epfd

	while(1)
	{
		eptc = epoll_wait(epfd,events,20,-1);
		for(i=0;i<eptc;i++)
		{
			if(sqlite3_open("project.db",&db)!=0)
			{
    			fprintf(stderr,"sqlite3_open err:%s\n",sqlite3_errmsg(db));
			}
			if(flag == 1){
				printf("database open successfully\n");
				flag =0;
			}
			if(events[i].data.fd == sockfd){
			acceptfd = accept(events[i].data.fd,\
			(struct sockaddr *)&clientaddr,&addrlen);//将每个客户端的文件描述符进行绑定
			event.data.fd = acceptfd;
			epoll_ctl(epfd,EPOLL_CTL_ADD,acceptfd,&event);//把acceptfd注册到epfd
			}
			else
			{
			//memset(buf,0,sizeof(buf));
			rlen = admin(events[i].data.fd); 
			if(rlen <=0){ //客户端断开 
					printf("connect disconnected\n");
					close(events[i].data.fd); //关闭连接
					epoll_ctl(epfd,EPOLL_CTL_DEL,events[i].data.fd,&event);
					sqlite3_close(db);
					flag = 1;
					//删除监听的客户端fd
					continue;
				}
			}
		}
	}

	return 0;
}
